package bean.managed;

import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.DepartmentEntityFacade;
import bean.session.RightEntityFacade;
import bean.session.RoleEntityFacade;
import bean.session.SystemUserEntityFacade;


import entity.DepartmentEntity;
import entity.RightEntity;
import entity.RoleEntity;
import entity.SystemUserEntity;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DualListModel;
import session.stateful.RightBean;

@ManagedBean(name = "RoleController")
@SessionScoped
public class RoleController extends AbstractBacking implements Serializable {

    List<RoleEntity> allRolesEntity = new ArrayList<RoleEntity>();
    List<RoleEntity> userRolesEntity = new ArrayList<RoleEntity>();
    List<String> allRolesString = new ArrayList<String>();
    List<String> userRolesString = new ArrayList<String>();
    private DualListModel<String> rolesPickList;

    public List<RoleEntity> getAllRoles() {

        //List<RoleEntity> allRoles = new ArrayList<RoleEntity>();
        allRolesEntity = ejbFacade.findAllIncludeArchived();

        return allRolesEntity;
    }

    public List<RoleEntity> getUserRoles() {

        //List<RoleEntity> allRoles = new ArrayList<RoleEntity>();
        userRolesEntity = new ArrayList(getList());

        return userRolesEntity;
    }

    public DualListModel<String> getRolesPickList() {
        if (rolesPickList == null) {
            //allRightsEntityList = new ArrayList<RightEntity>();
userRolesEntity = getUserRoles();
            //allRightsEntityList = ejbFacade.findAllIncludeArchived();
            for (int i = 0; i < getAllRoles().size(); i++) {
                if (!userRolesEntity.contains(getAllRoles().get(i))){
                allRolesString.add(getAllRoles().get(i).getRoleName());
                }
            }

            //userRightsEntityList = new ArrayList<RightEntity>(getList());
            for (int i = 0; i < getUserRoles().size(); i++) {
                userRolesString.add(getUserRoles().get(i).getRoleName());
            }

            rolesPickList = new DualListModel<String>(allRolesString, userRolesString);
            return rolesPickList;
        }
        return rolesPickList;
    }

    public void setRolesPickList(DualListModel<String> rolesPickList) {
        this.rolesPickList = rolesPickList;
    }

    public void updateUserRoles() {
//        System.out.println("I am here");
//        selectedUser.getRights().add(rightsPickList.getTarget().get(2));
//        getFacade().edit(selectedUser);
        //selectedUser.getRights();
        for (int i = 0; i < rolesPickList.getTarget().size(); i++) {
            //for (int j = 0; j < getList().size(); i++){
            if (getEjbFacade().findRole(rolesPickList.getTarget().get(i)) != null) {
                if (!getList().contains(getEjbFacade().findRole(rolesPickList.getTarget().get(i)))) {
                    getList().add(getEjbFacade().findRole(rolesPickList.getTarget().get(i)));
                }
            }
            // }
        }
        List<RoleEntity> allRolesInPickList = new ArrayList();
        for (int i = 0; i < rolesPickList.getTarget().size(); i++) {
            allRolesInPickList.add(getEjbFacade().findRole(rolesPickList.getTarget().get(i)));
        }

        Iterator itr = getList().iterator();
        while (itr.hasNext()) {

            if (!allRolesInPickList.contains(itr.next())) {
                itr.remove();
            }
        }


        selectedUser.setRoles(getList());
    selectedUser.modified(getLoginPerson());
        getFacade().edit(selectedUser);
//          rightsPickList=null;
//          allRights.clear();
//          userRights.clear();
    }
    private DepartmentEntity selectedDepartment;

    public DepartmentEntity getSelectedDepartment() {
        return selectedDepartment;
    }

    public void setSelectedDepartment(DepartmentEntity selectedDepartment) {
        this.selectedDepartment = selectedDepartment;
    }
    //private RightEntity right;
    private RoleEntity selectedRole;

    public RoleEntity getSelectedRole() {
        return selectedRole;
    }

    public void setSelectedRole(RoleEntity selectedRole) {
        this.selectedRole = selectedRole;
    }
    private List<DepartmentEntity> department;
    @EJB
    private bean.session.DepartmentEntityFacade facade2;

    public DepartmentEntityFacade getFacade2() {
        return facade2;
    }

    public void setFacade2(DepartmentEntityFacade facade2) {
        this.facade2 = facade2;
    }

    public List<DepartmentEntity> getDepartment() {
        department = new ArrayList<DepartmentEntity>();
        department = facade2.findAllIncludeArchived();

        return department;
    }

    public void setDepartment(List<DepartmentEntity> department) {
        this.department = department;
    }
    @ManagedProperty(value = "#{list}")
    private Collection<RoleEntity> list;

    public Collection<RoleEntity> getList() {
        return selectedUser.getRoles();
    }

    public void setList(Collection<RoleEntity> list) {
        this.list = list;
    }
    private String status;
    private SystemUserEntity curr;
    private DepartmentEntity de;

    public DepartmentEntity getDe() {
        return de;
    }

    public void setDe(DepartmentEntity de) {
        this.de = de;
    }
    private SystemUserEntity selectedUser;
    private String[] sel;

    public String[] getSel() {
        return sel;
    }

    public void setSel(String[] sel) {
        this.sel = sel;
    }
    private Collection<SystemUserEntity> user;
    private Map<String, String> ARs;

    public void setARs(Map<String, String> ARs) {
        this.ARs = ARs;
    }
    @EJB
    private bean.session.RoleEntityFacade ejbFacade;

    public RoleEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(RoleEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public Map<String, String> getARs() {

        List<RoleEntity> list1 = new ArrayList<RoleEntity>();
        list1 = ejbFacade.findAllIncludeArchived();
        ARs = new HashMap<String, String>();
        String[] k = new String[list1.size()];

        for (int i = 0; i < list1.size(); i++) {
            RoleEntity r = list1.get(i);
            k[i] = r.getRoleName();
            ARs.put(k[i], k[i]);
        }
        return ARs;

//        String[] res = facade2.getRolesInDepartment(selectedDepartment.getName());
//        ARs = new HashMap<String, String>();
//        for (int i = 0; i < res.length; i++) {
//            ARs.put(res[i], res[i]);
//        }
//
//        return ARs;
    }
    @EJB
    private bean.session.SystemUserEntityFacade facade;

    public RoleController() {
    }

    public SystemUserEntity getSelected() {

        if (curr == null) {
            curr = new SystemUserEntity();
        }
        return curr;
    }

    //  private List<RightEntity> selectedARs;
//    public List<RightEntity> getSelectedARs() {
//        //ARs = new ArrayList<RightEntity>();
//        return selectedARs;
//    }
//
//    public void setSelectedARs(List<RightEntity> selectedARs) {
//        selectedARs = new ArrayList<RightEntity>();
//
//        this.selectedARs = selectedARs;
//    }
    public String remove() {
        try {

            Collection<RoleEntity> result = getList();
            Collection<RoleEntity> result1 = new ArrayList<RoleEntity>();
            System.out.println("User Selected1111111111: " + curr);
            //for(RightEntity r:getList() ){System.out.println(r.getRightName()+"hhhhhhh ");}
            String[] lk = getSel();

            System.out.println(lk.length + "aaaaa");
            for (RoleEntity r : result) {
                boolean have = false;

                for (int i = 0; i < lk.length; i++) {
                    //check the list for existing rights

                    //System.out.println("bbbbbb1"+r.getRightName());
                    System.out.println("cccccccc1" + lk[i]);
                    if ((r.getRoleName().equalsIgnoreCase(lk[i]))) {


                        have = true;
                        break;

                    }
                }
                if (!have) {
                    result1.add(r);
                }

            }
            for (RoleEntity r1 : result1) {
                System.out.println(r1.getRoleName() + "mmmmmmm ");
            }

            setList(result1);
            curr.setRoles(result1);

            Collection<RightEntity> r = new ArrayList<RightEntity>();
            for (RoleEntity r1 : result1) {
                r.addAll(r1.getRights());
            }
            curr.setRights(r);
            getFacade().edit(curr);

            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AccessRightRemoved"));
            return "UserRole?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String update() {
        try {
            Collection<RoleEntity> result = getList();

            String[] lk = getSel();
            for (int i = 0; i < lk.length; i++) {
                boolean same = false;

                for (RoleEntity r : result) {
                    // System.out.println(lk[i]+"hhhhh"+r.getRightName());
                    if (r.getRoleName().equalsIgnoreCase(lk[i])) {
                        same = true;
                        break;
                    }

                }
                if (!same) {
                    System.out.println("lllll1 " + lk[i]);
                    RoleEntity r1 = getEjbFacade().findRole(lk[i]);
                    System.out.println("lllll");
                    curr.getRoles().add(r1);
                    curr.getRights().addAll(r1.getRights());
                }
            }

//            curr.setRights(result);
            //  for(RightEntity r:getAccessRight() ){System.out.println(r.getRightName()+"hhhhhhh");}


            getFacade().edit(curr);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("AcceesRightUpdated"));
            return "UserRole?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String departmentSelect(SelectEvent event) {
        System.out.println("De Selected: " + selectedDepartment);
        System.out.println("" + (null == (DepartmentEntity) event.getObject()));
        de = selectedDepartment;


        return "ViewRole?faces-redirect=true";
    }

    public String userSelect(SelectEvent event) {
        System.out.println("User Selected: " + selectedUser);
        System.out.println("" + (null == (SystemUserEntity) event.getObject()));
        curr = selectedUser;
        list = curr.getRoles();
        setList(selectedUser.getRoles());
        for (RoleEntity r : list) {
            System.out.println(r.getRoleName() + "vvvvvvvvv");
        }

        allRolesEntity.clear();
        userRolesEntity.clear();
        allRolesString.clear();
        userRolesString.clear();
        rolesPickList = null;
        return "UserRole?faces-redirect=true";
    }

    public String roleSelect(SelectEvent event) {
        System.out.println("User Selected: " + selectedRole);
        System.out.println("" + (null == (RoleEntity) event.getObject()));
        curr = selectedUser;


        for (RoleEntity r : list) {
            System.out.println(r.getRoleName() + "vvvvvvvvv");
        }


        allRolesEntity.clear();
        userRolesEntity.clear();
        allRolesString.clear();
        userRolesString.clear();
        rolesPickList = null;
        return "UserRole?faces-redirect=true";

    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void statusUpdate(String status) {
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage(status, null));
    }

    public void discard() {
        //reset current
        curr = new SystemUserEntity();
        selectedUser = curr;
    }

    public Collection<SystemUserEntity> getUser() {
        user = new ArrayList<SystemUserEntity>();
        user = selectedDepartment.getEmployees();

        return user;
    }

    public void setUsers(ArrayList<SystemUserEntity> msg) {
        this.user = msg;
    }

    public SystemUserEntity getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(SystemUserEntity selectedUser) {
        this.selectedUser = selectedUser;
    }

    public SystemUserEntity getCurrent() {
        return curr;
    }

    public void setCurrent(SystemUserEntity current) {
        this.curr = current;
    }

    public SystemUserEntityFacade getFacade() {
        return facade;
    }

    public void setFacade(SystemUserEntityFacade userBean) {
        this.facade = userBean;
    }
}
